<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>canvas点击事件</title>
</head>

<body>
    <canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">
        您的浏览器不支持 HTML5 canvas 标签。</canvas>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>

        $(function () {
            var myAction = {}, ctx;

            var dom = {
                canvas: $('#myCanvas')
            };

            $.extend(myAction, {
                initCanvas: function () {
                    ctx = dom.canvas[0].getContext("2d");

                    ctx.rect(10, 10, 100, 100);
                    ctx.rect(120, 10, 100, 100);
                    ctx.stroke();
                },
                getEventPosition: function (ev) {
                    var x, y;
                    if (ev.layerX || ev.layerX == 0) {
                        x = ev.layerX;
                        y = ev.layerY;
                    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
                        x = ev.offsetX;
                        y = ev.offsetY;
                    }
                    return { x: x, y: y };
                },
                initEvent: function () {
                    dom.canvas.on('click', function(e) {
                        var p = myAction.getEventPosition(e);
                        if (ctx.isPointInPath(p.x, p.y)) {
                            console.log(1);
                        } else {
                            console.log(2);
                        }
                    });                
                }
            });

            var init = function () {
                myAction.initCanvas();
                myAction.initEvent();
            }();
        })
    </script>
</body>

</html>